import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, customResponse } from '~/utils/response';
import { queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    // 读取请求体
    const { sampleNo, receiveStatus, sampleStatus, receiveDate, receiver } = await readBody(event);
    if (!sampleNo) throw new Error('委托单编号不能为空！');
    if (receiveStatus !== true && receiveStatus !== false) throw new Error('收样状态只能为true或false！');
    console.log(sampleNo, receiveStatus, sampleStatus, receiveDate, receiver);
    if (receiveStatus) {
      // 收样
      return useResponseSuccess({ code: 0, message: '收样成功' });
    } else {
      // 取消收样
      return useResponseSuccess({ code: 0, message: '取消成功' });
    }

    // let queryString;
    // const args = [];
    // /*================================ 生成样品台账 ================================ */
    // // 获取样品委托信息
    // const orderColumns = [
    //   'clientName',
    //   'contactPerson',
    //   'orderNo',
    //   'sampleName',
    //   'modelSpec',
    //   'quantity',
    //   'testItems',
    //   'sampleHandling'
    // ];
    // const addColumns = [
    //   'sampleNo',
    //   'sampleStatus',
    //   'receiver',
    //   'receiveDate',
    //   'createTime',
    //   'updateTime'
    // ]

    // queryString = `SELECT ${orderColumns.join(', ')} FROM samplelists WHERE orderNo = ?`;
    // const result = <any[]>await queryDatabase(queryString, orderNo);
    // if (result.length === 0) throw new Error('委托单不存在！');
    // if (result.length > 1) throw new Error('委托单存在重复！');

    // const data = { ...result[0] };  // 浅拷贝result[0]对象,防止修改result[0]对象

    // // 插入数据库（假设表结构包含所有字段）
    // const fields = [...orderColumns, ...addColumns].join(', ');

    // const placeholders = Object.keys(processData)
    //   .map(() => '?')
    //   .join(', ');
    // queryString = `INSERT INTO testorder (orderNo, ${fields}) VALUES (?, ${placeholders})
    //         ON DUPLICATE KEY UPDATE ${Object.keys(processData)
    //           .map((k) => `${k}=VALUES(${k})`)
    //           .join(', ')}`;

    // // 更新收样状态
    // queryString = `UPDATE testorder SET receiveStatus = ? updateTime = ? WHERE orderNo = ?`;
    // await queryDatabase(queryString,, [data.receiveStatus, orderNo]);

    // return useResponseSuccess({ code: 0, message: '更新成功' });
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
